﻿namespace Atomic.Mvc.ViewEngines
{
    using System;
    using System.Threading;
    using System.Web.Razor.Generator;
    using System.Web.WebPages.Razor;

    /// <summary>
    /// Rzaor 模板提供程序。
    /// </summary>
    public class AtomicRzaorProvider
    {
        /// <summary>
        /// 初始化并原子化。
        /// </summary>
        private static int _initialized;

        /// <summary>
        /// Razor 模板编译事件。
        /// </summary>
        private readonly IRazorCompilationEvent _razorCompilationEvent = null;

        /// <summary>
        /// 初始化 Rzaor 模板提供程序。
        /// </summary>
        private AtomicRzaorProvider()
        {
            this._razorCompilationEvent = new RazorCompilationEvent();

            RazorBuildProvider.CodeGenerationStarted += RazorBuildProviderCodeGenerationStarted;
            RazorBuildProvider.CodeGenerationCompleted += RazorBuildProviderCodeGenerationCompleted;
        }

        /// <summary>
        /// 代码编译开始事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RazorBuildProviderCodeGenerationStarted(object sender, EventArgs e)
        {
            var provider = (RazorBuildProvider)sender;
            this._razorCompilationEvent.CodeGenerationStarted(provider);
        }

        /// <summary>
        /// 代编译完成事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RazorBuildProviderCodeGenerationCompleted(object sender, CodeGenerationCompleteEventArgs e)
        {
            var provider = (RazorBuildProvider)sender;
            this._razorCompilationEvent.CodeGenerationCompleted(provider, e);
        }

        /// <summary>
        /// 初始化 Rzaor 模板提供程序。
        /// </summary>
        public static void EnsureInitialized()
        {
            var uninitialized = Interlocked.CompareExchange(ref _initialized, 1, 0) == 0;
            if (uninitialized)
                new AtomicRzaorProvider();
        }
    }
}